package com.zhang.third.day02;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @title: reduce 计算avg
 * @author: zhang
 * @date: 2022/4/2 15:40
 */
public class Example8 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .fromElements(1, 3, 2, 5, 7, 2, 5, 4, 3, 2, 9)
                .map(r -> Tuple2.of(r, 1))
                .returns(Types.TUPLE(Types.INT, Types.INT))
                .keyBy(r -> 1)
                .reduce(new ReduceFunction<Tuple2<Integer, Integer>>() {
                    @Override
                    public Tuple2<Integer, Integer> reduce(Tuple2<Integer, Integer> value1, Tuple2<Integer, Integer> value2) throws Exception {
                        return Tuple2.of(
                                value1.f0 + value2.f0,
                                value1.f1 + value2.f1
                        );
                    }
                })
                .map(new MapFunction<Tuple2<Integer, Integer>, String>() {
                    @Override
                    public String map(Tuple2<Integer, Integer> value) throws Exception {
                        return "总和为：" + value.f0 + ",条数为：" + value.f1 + ",平均值为：" + ((double) value.f0 / value.f1);
                    }
                })
                .print();


        env.execute();
    }
}
